/**
 * 用于筛选作品的工具函数
 */

/**
 * 按类别筛选作品
 * @param {Array} works - 作品数组
 * @param {String} category - 筛选类别
 * @returns {Array} - 筛选后的作品数组
 */
export const filterWorksByCategory = (works, category) => {
    if (!category || category === 'all') {
      return works;
    }
    
    return works.filter(work => work.category.includes(category));
  };
  
  /**
   * 通过搜索关键词筛选作品
   * @param {Array} works - 作品数组
   * @param {String} keyword - 搜索关键词
   * @returns {Array} - 筛选后的作品数组
   */
  export const filterWorksByKeyword = (works, keyword) => {
    if (!keyword) {
      return works;
    }
    
    const lowerKeyword = keyword.toLowerCase();
    
    return works.filter(work => 
      work.title.toLowerCase().includes(lowerKeyword) || 
      work.description.toLowerCase().includes(lowerKeyword) ||
      work.category.some(cat => cat.toLowerCase().includes(lowerKeyword))
    );
  };
  
  /**
   * 按ID查找作品
   * @param {Array} works - 作品数组
   * @param {Number|String} id - 作品ID
   * @returns {Object|null} - 找到的作品或null
   */
  export const findWorkById = (works, id) => {
    const workId = parseInt(id, 10);
    return works.find(work => work.id === workId) || null;
  };
  
  /**
   * 将作品按时间排序（假设works中有创建时间字段）
   * @param {Array} works - 作品数组
   * @param {Boolean} ascending - 是否升序排列
   * @returns {Array} - 排序后的作品数组
   */
  export const sortWorksByDate = (works, ascending = false) => {
    return [...works].sort((a, b) => {
      const dateA = a.createdAt ? new Date(a.createdAt) : new Date(0);
      const dateB = b.createdAt ? new Date(b.createdAt) : new Date(0);
      
      return ascending ? dateA - dateB : dateB - dateA;
    });
  };
  
  /**
   * 获取所有唯一的作品类别
   * @param {Array} works - 作品数组
   * @returns {Array} - 所有唯一类别的数组
   */
  export const getUniqueCategories = (works) => {
    const allCategories = works.reduce((acc, work) => {
      return [...acc, ...work.category];
    }, []);
    
    return [...new Set(allCategories)];
  };